package com.zoran.study.spring.validation.validator;

import com.zoran.study.spring.validation.constraint.SecureText;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Secure text validator.
 *
 * @author Winter Gao
 *
 */
public class SecureTextValidator implements ConstraintValidator<SecureText, String> {

    private Pattern pattern;

    @Override
    public void initialize(SecureText constraintAnnotation) {
        final String regex = constraintAnnotation.pattern();
        if (regex == null || regex.trim().length() == 0) {
            throw new IllegalArgumentException("Secure text pattern cannot be null or empty");
        }

        pattern = Pattern.compile(constraintAnnotation.pattern());
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null || value.trim().length() == 0) {
            return true;
        }

        Matcher m = pattern.matcher(value);
        return m.matches();
    }

}
